#include <head.h>
#include <event2/bufferevent.h>
#include <event2/buffer.h>
#include <event2/listener.h>
#include <event2/util.h>
#include <event2/event.h>
#include "./request_process.h"
int get_line(int cfd, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;
    while ((i < size-1) && (c != '\n')) {  
        n = recv(cfd, &c, 1, 0);
        if (n > 0) {     
            if (c == '\r') {            
                n = recv(cfd, &c, 1, MSG_PEEK);
                if ((n > 0) && (c == '\n')) {              
                    recv(cfd, &c, 1, 0);
                } else {                       
                    c = '\n';
                }
            }
            buf[i] = c;
            i++;
        } else {      
            c = '\n';
        }
    }
    buf[i] = '\0';
    
    if (-1 == n)
    	i = n;

    return i;
}
char* get_request_fileName(struct bufferevent *bev)
{
    char *buf =calloc(1,1000);
    char method[20],protocl[20];
    char *fileName =calloc(100,1);
    CLEAR_ARRAY(method);
    CLEAR_MEM(fileName,100);
    CLEAR_ARRAY(protocl);
    if(!buf){
        return NULL;
    }
    int ret =0;
    ret  =bufferevent_read(bev,buf,1000);
    if(ret>0){
        printf("%s",buf);
        sscanf(buf,"%[^ ]%[^ ]%[^ ]" ,method,fileName,protocl);
        printf("method:%s fileName:%s protocol:%s\n",method,fileName,protocl);
    }
    else{
        printf("invaild request head!\n");
        free(fileName);
        fileName =NULL;

    }
    /*
    while(1){
        CLEAR_MEM(buf,1000);
        ret = get_line(fd,buf,1000);
        if(ret<0){
            break;
        }
    }
    */
end:
    free(buf);
    return fileName;
}
void send404_page(struct bufferevent *bev)
{
    char *buf =calloc(1,1000);
    if(!buf){
        return;
    }
    snprintf(buf,1000,"HTTP/1.1 404 ERROR\r\n\r\n%s\r\n",ERROR_RESPONSE);
    bufferevent_write(bev,buf,strlen(buf));
    void closeConnection(struct bufferevent *bev);
    //closeConnection(bev);
    free(buf);
}
void closeConnection(struct bufferevent *bev)
{
    bufferevent_free(bev);
    
}